<template>
  <div class="login-box">
    <!-- 头部 -->
    <div class="header-box">
      <div class="content-box  flex jc-sb ai-c">
        <img src="@/assets/login-logo.png" @click="toHome()" style="cursor: pointer"/>
        <img src="@/assets/login-hot.png" />
      </div>
    </div>
    <!-- 登录 -->
    <div class="content">
      <div class="content-box flex jc-fe ai-c">
        <div class="login-module flex ai-c">
          <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" class="demo-ruleForm">
            <el-form-item prop="username">
              <el-input placeholder="请输入账号" v-model="ruleForm.username">
                <template slot="prepend">
                  <i class="el-icon-user-solid"></i>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="telephone">
              <el-input placeholder="请输入手机号" v-model="ruleForm.telephone">
                <template slot="prepend">
                  <i class="el-icon-mobile-phone"></i>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="authCode">
              <el-input placeholder="验证码" type="text" v-model="ruleForm.authCode">
                <template slot="prepend">
                  <i class="el-icon-message"></i>
                </template>
                <template slot="append">
                  <span  @click="sendMessage()">{{btnText}}</span>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input placeholder="密码" type="password" v-model="ruleForm.password">
                <template slot="prepend">
                  <i class="el-icon-key"></i>
                </template>
              </el-input>
            </el-form-item>
            <div class="flex check-box" style="justify-content: space-between; font-size:14px">
              <el-checkbox v-model="agree">同意 <a href="#" @click="findRegistr()">《服务条款》</a></el-checkbox>
              <span style="color:red;cursor: pointer" @click="login()">返回登录</span>
            </div>
            <el-form-item>
              <el-button type="danger" @click="submitForm('ruleForm')">注册</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <!-- 底部 -->
    <Footer />
    <div style="padding: 20px 0 30px;">
    </div>
    <!-- 服务条款 -->
    <el-dialog title="江铃晶马商城用户注册协议" :visible.sync="dialogVisible" width="80%" class="treaty">
        <p v-html="registrDetails.description"></p>
    </el-dialog>
  </div>
</template>

<script>
import Footer from "@/components/Footer.vue";
export default {
  components: {
    Footer,
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号或手机号"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } {
        callback();
      }
    };
    var validatePass3 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass4 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } {
        callback();
      }
    };
    return {
        registrDetails:'',
        token:'',
        ruleForm: {
        username: "",
        password: "",
        telephone: "",
        authCode: ""
      },
      rules: {
        username: [{ validator: validatePass, trigger: "blur" }],
        password: [{ validator: validatePass2, trigger: "blur" }],
        telephone: [{ validator: validatePass3, trigger: "blur" }],
        authCode: [{ validator: validatePass4, trigger: "blur" }],
      },
      dialogVisible: false,
      agree: true,
      btnText: "获取验证码",
      btnDisabled: false,
      isLogin: "getPwd"
    };
  },
    methods: {
    //返回登录界面  
    login(){
        this.$router.push({ path: '/login'})
    },
    //获取注册条款详情
    findRegistr(){
        this.$http.get('/bot_menu/find-registr').then((response) => {
            this.registrDetails = response.data;
            this.dialogVisible = true;
            console.log(this.registrDetails);
        })
    },
    submitForm(formName) {
      let _this = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
            this.$http.post('/sso/register?username='+this.ruleForm.username+"&password="+this.ruleForm.password
            +"&telephone="+this.ruleForm.telephone+"&authCode="+this.ruleForm.authCode,{},{
                headers: {'content-type':'x-www-form-urlencoded'}
            }).then(function (response) {
                if(response!=null){
                    console.log(response.code);
                    if(response.code==200){
                        _this.$message({
                            type: 'success',
                            message: '注册成功!',
                            duration:2000
                        });
                        _this.$router.push({ path: '/login'})    
                    }else{
                        _this.$message({
                            type: 'error',
                            message: '注册失败!',
                            duration:1000
                        });
                    }
                }
            })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    sendMessage() {
        this.$http.get('/sso/getAuthCode?telephone='+this.ruleForm.telephone).then( (response) => {
            console.log(response.code==200);
        })
        if (this.btnDisabled) {
            return;
        }
        this.getSecond(60);
    },
    toHome(){
      this.$router.push({ path: '/'})
    },
    //发送验证码
    getSecond(wait) {
      let _this = this;
      let _wait = wait;
      if (wait == 0) {
        this.btnDisabled = false;
        this.btnText = "获取验证码"
        wait = _wait;
      } else {
        this.btnDisabled = true;
        this.btnText = "验证码(" + wait + "s)"
        wait--;
        setTimeout(function () {
          _this.getSecond(wait);
        },
          1000);
      }
    },
    getCode () { // 非静默授权，第一次有弹框
      const code = this.getUrlParam('code') // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
      const local = window.location.href
      if (code == null || code === '') {
        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0a8fc3658d949fa1&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect'
      } else {
        //通过code获取openid
        window.localStorage.setItem('code', code);
       // alert(code)
        //this.getOpenId(code) //把code传给后台获取用户信息
      }
    },
    getOpenId (code,memberId) { // 通过code获取 openId等用户信息，/api/user/wechat/login 为后台接口
       let _this = this

      this.$http.get('/we-chat/get-openid?code='+code+'&memberId='+memberId).then((res) => {
        //let datas = res.data
        window.console.log(res.data)
        if (res.code === 200 ) {
            window.localStorage.setItem('openid', res.data.openid);
            console.log('成功')
          _this.$router.push({ path: '/'})
        }
      }).catch((error) => {
        alert(error);
      })
    },
    getUrlParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]); return null;
    },
    _isMobile() {
      let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
      return flag;
    }

  },
  created() {
    if(this._isMobile()){
      this.getCode()
    }


  }

};
</script>

<style lang="scss" scoped>
.header-box {
  height: 80px;
  background: #fff;
  margin-top: -110px;
  img {
    height: 100%;
  }
}
.diver {
  display: block;
  width: 1px;
  height: 14px;
  background-color: #999;
  margin: 0 16px;
}
.content {
  height: calc(100vh - 170px);
  background: url("~@/assets/login-bg.png") no-repeat center;
  .login-module {
    width: 400px;
    padding: 40px 40px 20px;
    box-sizing: border-box;
    background: #fff;
    /deep/ .el-form {
      width: 100%;
    }
    /deep/ .el-button {
      width: 100%;
    }
  }
}
.root-class {
  font-size: 14px;
  color: #999;
}
.treaty {
  text-align: left;
}
h5 {
  font-size: 20px;
  margin-top: 20px;
}
.forget {
  cursor: pointer;
}
.check-box {
  margin: 16px 0;
  /deep/ .el-checkbox__label {
    color: #409eff;
  }
}

/deep/ .el-dialog__title {
  font-size: 20px;
  font-weight: 700;
}
/deep/ .el-dialog__body {
  padding-top: 10px;
}
/deep/ .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #409eff;
  border-color: #409eff;
}
/deep/ .el-input-group__append {
  cursor: pointer;
}

/*手机端*/
@media (min-width: 320px) and (max-width: 800px) {
  .header-box{
    margin-top: -76px;
    width: 100%;
  }
  .content .login-module{
    width:90%;
    margin: 0 auto;
  }
}
</style>
